package com.gaff.emp.core.modules.sys.controller.dict;

import com.gaff.emp.core.EmpException;
import com.gaff.emp.core.R;
import com.gaff.emp.core.modules.auth.annotation.Auth;
import com.gaff.emp.core.modules.sys.controller.dict.form.CreateForm;
import com.gaff.emp.core.modules.sys.controller.dict.form.DeleteForm;
import com.gaff.emp.core.modules.sys.controller.dict.form.UpdateForm;
import com.gaff.emp.core.modules.sys.entity.SysDict;
import com.gaff.emp.core.modules.sys.service.SysDictService;
import com.gaff.emp.core.syslog.annotation.SysOperaLog;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/sys/dict")
public class SysDictController {

    @Autowired
    private SysDictService sysDictService;

    @GetMapping("/list")
    @ApiOperation("分页获取字典列表")
    @SysOperaLog(value = "分页获取字典列表", isPersistence = false)
    @Auth(perm = "dict")
    public R list(@RequestParam Map<String, Object> params) {
        return R.ok(sysDictService.queryDictsByPage(params));
    }

    @PostMapping("/create")
    @ApiOperation("新增字典")
    @SysOperaLog(value = "新增字典")
    @Auth(perm = "dict")
    public R create(@RequestBody @Valid CreateForm form, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new IllegalArgumentException(bindingResult.getFieldError().getDefaultMessage());
        }
        sysDictService.createDict(form);
        return R.ok();
    }

    @GetMapping("/info/{id}")
    @ApiOperation("获取字典信息")
    @SysOperaLog(value = "获取字典信息", isPersistence = false)
    @Auth(perm = "dict")
    public R info(@PathVariable("id") Integer id) {
        SysDict dict = sysDictService.queryDictById(id);
        if (dict == null) {
            throw new EmpException("字典不存在");
        }
        return R.ok(dict);
    }

    @PostMapping("/update")
    @ApiOperation("更新字典")
    @SysOperaLog(value = "更新字典")
    @Auth(perm = "dict")
    public R update(@RequestBody @Valid UpdateForm form, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new IllegalArgumentException(bindingResult.getFieldError().getDefaultMessage());
        }
        sysDictService.updateDict(form);
        return R.ok();
    }

    @PostMapping("/delete")
    @ApiOperation("删除字典")
    @SysOperaLog(value = "删除字典")
    @Auth(perm = "dict")
    public R delete(@RequestBody @Valid DeleteForm form, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new IllegalArgumentException(bindingResult.getFieldError().getDefaultMessage());
        }
        sysDictService.deleteById(form.getId());
        return R.ok();
    }

}
